package routers

import (
	"coding.net/vco/mder/models"
	"coding.net/vco/mder/modules/coding"
	"coding.net/vco/mder/modules/log"
	"coding.net/vco/mder/modules/util"
	"encoding/json"
	"fmt"
	"github.com/Unknwon/com"
	"github.com/Unknwon/macaron"
	"io/ioutil"

	"path/filepath"
)

//首页
func Home(ctx *macaron.Context) {
	ctx.HTML(200, tpl("index"), ctx.Data)
}

func isExist(path string) bool {
	return com.IsExist(path) || com.IsExist(path+".md")
}

func View(ctx *macaron.Context) {
	uri := ctx.Params("*")
	path := fmt.Sprintf("%s/%s", coding.DATA_PATH, uri)
	if !isExist(path) {
		//TODO 404
		ctx.HTML(404, tpl("404"), ctx.Data)
	} else if com.IsDir(path) {
		//目录
		ctx.HTML(200, tpl("archive"), ctx.Data)
	} else {
		if com.IsExist(path + ".md") {
			ctx.HTML(200, tpl("article"), ctx.Data)
		}

	}

}

func Robots(ctx *macaron.Context) {
	robots, _ := ioutil.ReadFile("robots.txt")
	ctx.Write(robots)
}

//TODO atom rss
//https://github.com/gorilla/feeds
func Rss(ctx *macaron.Context) {
	//ctx.XML()
}

func Atom(ctx *macaron.Context) {

}

func Archive(ctx *macaron.Context) {

}

func About(ctx *macaron.Context) {
	ctx.HTML(200, tpl("about"), ctx.Data)
}

//webhook
func Webhook(ctx *macaron.Context) {

	body, _ := ioutil.ReadAll(ctx.Req.Body)
	push := coding.CodingPush{}
	json.Unmarshal(body, &push)
	log.Debug("-------webhook-----:", push)
	if push.ValidateToken() {
		if push.After != "" {
			globalKey, project := coding.ParseRepository(push.Repository.Url)
			models.RefreshMderToml()
			coding.Rebuild(globalKey, project, push.Ref)
		}
	}
	msg := "Coding！ 让开发更简单"
	ctx.JSON(200, util.ApiSuccess(msg))

}

func tpl(path string) string {
	mder := models.NewMder()
	dest, _ := filepath.Rel("", fmt.Sprintf("theme/%s/%s", mder.Blog.Theme, path))
	return dest

}
